package com.ailk.kbi.kbiwarden.wsi.util

import groovy.sql.Sql

import java.util.ArrayList

import com.ailk.kbi.kbiwarden.wsi.exception.WSI_ERROR;
import com.ailk.kbi.kbiwarden.wsi.exception.WsiException;
import com.ailk.kbi.kbiwarden.wsi.vo.ColumnVO;
import com.ailk.kbi.kbiwarden.wsi.vo.QueryVO;
import com.ailk.kbi.kbiwarden.wsi.vo.WhereVO;

class SQLUtil {

	static Sql getDB2Instance(){
		Sql sql
		try{
			SystemUtil systemUtil = new SystemUtil()
			sql = Sql.newInstance(systemUtil.getDbsURL(), systemUtil.getDbsUser(), systemUtil.getDbsPassword(), "com.ibm.db2.jcc.DB2Driver")
		}
		catch(Throwable t){
			println t
			throw new WsiException(WSI_ERROR.ER_004_QUERY)
		}
		sql
	}

	static String getWhereString(ArrayList<WhereVO> wheres,ArrayList<ColumnVO> columns){
		/*拼where字符串*/
		String whereString = ""
		String linkString = "where"

		wheres.each {whereVO ->
			ColumnVO columnVO = columns.find{column->column.name == whereVO.column}
			if(columnVO != null && columnVO.type.equalsIgnoreCase("DA")){
				/*日期类型*/
				whereString = whereString + " " + linkString + " " + whereVO.toDB2DateString()
			}
			else if(columnVO != null && (columnVO.type.equalsIgnoreCase("INTEGER"))){
				whereString = whereString + " " + linkString + " " + whereVO.toNumberString()
			}
			else{
				whereString = whereString + " " + linkString + " " + whereVO
			}
			linkString = "and"
		}
		whereString
	}

	static String getColumnString(QueryVO queryVO){
		String columnString = ""
		queryVO.columns.each { column ->
			String temp = column.name
			if(column.type == "DA"){
				temp = "rtrim(char(year(${column.name}))) || substr(digits(month(${column.name})),9) || substr(digits(day(${column.name})),9) ${column.name}"
			}

			columnString = columnString + temp + ","
		}
		/*去掉最后一个,*/
		columnString = columnString.substring(0, columnString.length() - 1)
		columnString
	}

	static String getOrderString(QueryVO queryVO){
		String orderString = ""
		if(queryVO.order != null && !queryVO.order.isEmpty()){
			orderString = " order by " + queryVO.order;
		}
		orderString
	}
}
